import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { avatarUrl } = await req.json();

    if (!avatarUrl || typeof avatarUrl !== 'string') {
      return NextResponse.json({ error: '无效的头像URL' }, { status: 400 });
    }
    
    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: { avatar: avatarUrl },
      select: {
          id: true,
          username: true,
          avatar: true,
      },
    });

    return NextResponse.json(updatedUser, { status: 200 });
  } catch (error) {
    console.error('更新头像失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 